package com.qiangesoft.blog.core.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.blog.common.constants.FieldConstants;
import com.qiangesoft.blog.common.mvc.PageQuery;
import com.qiangesoft.blog.common.mvc.PageResultVO;
import com.qiangesoft.blog.common.result.ResponseResult;
import com.qiangesoft.blog.common.utils.HTMLUtils;
import com.qiangesoft.blog.common.utils.PageUtils;
import com.qiangesoft.blog.core.entity.BlogComment;
import com.qiangesoft.blog.core.mapper.BlogCommentMapper;
import com.qiangesoft.blog.core.pojo.dto.CommentDTO;
import com.qiangesoft.blog.core.pojo.vo.ArticleListVO;
import com.qiangesoft.blog.core.pojo.vo.CommentVO;
import com.qiangesoft.blog.core.pojo.vo.ReplyVO;
import com.qiangesoft.blog.core.pojo.vo.SystemCommentVO;
import com.qiangesoft.blog.core.service.IBlogCommentService;
import com.qiangesoft.blog.system.entity.SysUser;
import com.qiangesoft.blog.system.exception.BusinessException;
import com.qiangesoft.blog.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 博客评论 服务实现类
 * </p>
 *
 * @author qiange
 * @since 2023-06-05
 */
@Service
@RequiredArgsConstructor
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment> implements IBlogCommentService {

    private final SysUserMapper userMapper;

    @Override
    public Integer countCommentByArticleId(Long articleId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BlogComment>()
                .eq(BlogComment::getArticleId, articleId));
    }

    /**
     * 评论列表
     *
     * @param keywords
     * @return
     */
    @Override
    public PageResultVO<SystemCommentVO> listComment(PageQuery pageQuery, String keywords) {
        PageResultVO<SystemCommentVO> pageResultVO = new PageResultVO<>();
        Integer pageNum = pageQuery.getPageNum();
        Integer pageSize = pageQuery.getPageSize();
        pageResultVO.setPageNum(pageNum);
        pageResultVO.setPageSize(pageSize);

        Page<SystemCommentVO> page = baseMapper.selectPageList(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), keywords);
        pageResultVO.setTotal(page.getTotal());
        pageResultVO.setPages(page.getPages());
        pageResultVO.setResults(page.getRecords());
        return pageResultVO;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult deleteBatch(List<Integer> ids) {
        baseMapper.deleteBatchIds(ids);
        return ResponseResult.success();
    }


    //-----------------------web端方法开始-------------
    @Override
    public PageResultVO<ArticleListVO> comments(Long articleId, PageQuery pageQuery) {
        PageResultVO pageResult = new PageResultVO();
        pageResult.setPageNum(pageQuery.getPageNum());
        pageResult.setPageSize(pageQuery.getPageSize());

        QueryWrapper<BlogComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstants.ARTICLE_ID, articleId)
                .isNull(FieldConstants.PARENT_ID)
                .orderByDesc(FieldConstants.ID);
        Page<BlogComment> pages = baseMapper.selectPage(new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize()), queryWrapper);
        List<BlogComment> comments = pages.getRecords();
        pageResult.setTotal(pages.getTotal());
        pageResult.setPages(pages.getPages());
        if (CollectionUtils.isEmpty(comments)) {
            return pageResult;
        }

        List<CommentVO> commentList = new ArrayList<>();
        for (BlogComment comment : comments) {
            SysUser userAuth = userMapper.selectById(comment.getUserId());
            List<ReplyVO> replyVOList = baseMapper.listReplies(comment.getId());
            CommentVO dto = new CommentVO();
            dto.setId(comment.getId());
            dto.setUserId(comment.getUserId());
            dto.setContent(comment.getContent());
            dto.setCreateTime(Timestamp.valueOf(comment.getCreateTime()).getTime());
            dto.setAvatar(userAuth.getAvatar());
            dto.setNickname(userAuth.getNickname());
            dto.setReplyList(replyVOList);
            commentList.add(dto);
        }
        pageResult.setResults(commentList);
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult addComment(CommentDTO commentDTO) {
        if (commentDTO.getReplyUserId() != null && commentDTO.getUserId() == null) {
            throw new BusinessException("非法请求评论!");
        } else {
            if (commentDTO.getUserId() != null) {
                throw new BusinessException("非法请求评论!");
            }
        }

        // 过滤标签
        commentDTO.setCommentContent(HTMLUtils.deleteTag(commentDTO.getCommentContent()));
        BlogComment comment = BlogComment.builder()
                .userId(StpUtil.getLoginIdAsLong())
                .replyUserId(commentDTO.getReplyUserId())
                .articleId(commentDTO.getArticleId())
                .content(commentDTO.getCommentContent())
                .parentId(commentDTO.getParentId()).createTime(LocalDateTime.now())
                .build();
        int rows = baseMapper.insert(comment);
       /* // 判断是否开启邮箱通知,通知用户
        if (websiteConfig.getIsEmailNotice().equals(TRUE)) {
            notice(comment);
        }*/
        return rows > 0 ? ResponseResult.success(comment) : ResponseResult.error("评论失败");
    }

    @Override
    public ResponseResult repliesByComId(Integer commentId) {
        Page<BlogComment> page = baseMapper.selectPage(new Page<>(PageUtils.getPageNo(), PageUtils.getPageSize()), new QueryWrapper<BlogComment>().eq(FieldConstants.PARENT_ID, commentId));
        List<ReplyVO> result = new ArrayList<>();
        for (BlogComment comment : page.getRecords()) {
            SysUser userAuth = userMapper.selectById(comment.getUserId());
            SysUser replyUser = userMapper.selectById(comment.getReplyUserId());
            ReplyVO dto = new ReplyVO();
            dto.setId(comment.getId());
            dto.setAvatar(userAuth.getAvatar());
            dto.setNickname(userAuth.getNickname());
            dto.setContent(comment.getContent());
//            dto.setCreateTime(comment.getCreateTime());
            dto.setParentId(commentId);
            dto.setReplyNickname(replyUser.getNickname());
            result.add(dto);
        }
        return ResponseResult.success(result);
    }
}
